// $Id: $

function get_traveltime() {
  if ($(':text[@value!="0"]:last').size() == 0) return;

  // building URL
  var p; 
  var f_itens = [];
  $('form table tr:gt(0):lt(5)').each(function() {
    f_itens.push( $('td:eq(1) input', this).attr('name')+ '=' 
                 +$('td:eq(2)', this).text());
  });
  p = $(':input').not(':checkbox,:button,:submit').serialize() 
      + '&' + f_itens.join('&') + '&calc=1&nap=1';

  $.get('/0/Fleet/send.php?'+p, function(data) {
    tt = data.match(/time: (.*?)\./m);
    if (tt) {
      var months = {'Jan':0, 'Feb':1, 'Mar':2, 'Apr':3, 'May':4,  'Jun':5,
                    'Jul':6, 'Aug':7, 'Sep':8, 'Oct':9, 'Nov':10, 'Dec':11};
      var dt = tt[1].match(/^(\w+) (\d+) - (\d+):(\d+):(\d+)/);
      
      var df = new Date();
      df.setMonth(months[dt[1]]);
      df.setDate(dt[2]);
      df.setHours(dt[3]);
      df.setMinutes(dt[4]);
      df.setSeconds(dt[5]);

      var ts = (df.getTime() - new Date().getTime()) / (60*60*1000);

      var h = parseInt(ts);
      var mt = (ts - h) * 60;
      var m = parseInt(mt);
      var st = (mt - m) *60;
      var s = parseInt(st);

      ftt = tt[1] + ' ('+h+'h '+m+'m '+s+'s)';

      $('#awplus_ttc').text(ftt);
    }
    else $('#awplus_ttc').text('Fill form correctly!'); 
  });
}

function get_system_info () {
  sid = $(':text[@name=destination2]').val();
  sid = sid ? sid : $('#awplus_planet').val();
  
  $('#system_content').getSystemData(sid, true);
}

$(document).ready(function() {
  // Remove traveltime calculator checkbox
  $(':checkbox[@name="calc"]').parent().empty().attr({id: 'awplus_ttc', colspan:2});
  
  // Add event handler
  $('select,:text[@name=destination2],:text:last').change(get_traveltime);
  
  $('select[@name=destination], :text[@name=destination2]').change(get_system_info);

  // Add a button to force check travel time
  $('#awplus_content form table tr:gt(8):contains(Arrival) td:first').append(' <input type="button" value="Check" id="ap_bt_tt" class="smbutton" />');
  $('#ap_bt_tt').click(get_traveltime);
  
  // System info show
  $('#awplus_content table:first').after('<div id="system_content"></div>');
  get_system_info();
});
